package cn.edu.xmist.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author zhongjinbin (jinbin.zhong@nascent.cn)
 * @version 1.0.0
 * @date 2021/1/8 13:46
 * @description 1.创建Callable接口的实现类，并实现call()方法，然后创建该实现类的实例（从java8开始可以直接使用Lambda表达式创建Callable对象）
 * 2.使用FutureTask类来包装Callable对象，该FutureTask对象封装了Callable对象的call()方法的返回值
 * 3.使用FutureTask类来包装Callable对象，该FutureTask对象封装了Callable对象的call()方法的返回值 4.
 * 4.调用FutureTask对象的get()方法来获得子线程执行结束后的返回值
 */
public class CallableAndFutureTest {

    public static void main(String[] args) {
        //
        Callable<Integer> call =
                new Callable<Integer>() {
                    @Override
                    public Integer call() throws Exception {
                        System.out.println("计算线程正在计算结果。。。。。。");
                        Thread.sleep(3000);
                        return 1;
                    }
                };
        FutureTask<Integer> future = new FutureTask(call);
        new Thread(future, "有返回值的线程").start();

        try {
            System.out.println("子线程的返回值：" + future.get(4000, TimeUnit.SECONDS));
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
